package org.example.shop.controller;

import jakarta.servlet.http.HttpSession;
import org.example.shop.dto.CarItem;
import org.example.shop.entity.Users;
import org.example.shop.service.ShopcarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class ShopCarController {

    @Autowired
    private ShopcarService shopcarService;

    @GetMapping("/car")
    public String car(Model model, HttpSession session) {
        Users user = (Users)session.getAttribute("loginUser");
        if(user==null){
            return "redirect:/user/login";
        }
        //获取购物车数据
        List<CarItem> car = shopcarService.getCar(user.getId());
        Double totalPrice = shopcarService.getTotalPrice(user.getId());
        model.addAttribute("totalPrice", totalPrice);
        model.addAttribute("car",car);

        return "cart";
    }
    @PostMapping("/car/add")
    @ResponseBody
    public String add(@RequestParam int goodid,int num, HttpSession session) {
        //1. 找到登录用户的id
        Users user = (Users) session.getAttribute("loginUser");
        if(user==null){
            return "fail:user";
        }
        int userid = user.getId();
        System.out.println("添加购物车："+userid);
        //2. 添加到购物车
       boolean isAdd =  shopcarService.addCar(userid,goodid,num);
       if(isAdd){
           return "success";
       }else{
           return "fail";
       }

    }

}
